package com.neusoft.bizcore.notice.notification.repository.impl;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.notice.notification.model.NoticeRecord;
import com.neusoft.bizcore.notice.notification.model.QNoticeRecord;
import com.neusoft.bizcore.notice.notification.model.enums.SendStatus;
import com.neusoft.bizcore.notice.notification.repository.CustomizedNoticeRecordRepository;
import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedNoticeRecordRepositoryImpl extends AbstractRepository
        implements CustomizedNoticeRecordRepository {

    @Override
    public List<NoticeRecord> index(final Searchable searchable) {
        final QNoticeRecord qNotice = QNoticeRecord.noticeRecord;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<NoticeRecord> query = this.query().selectFrom(qNotice);
        query.where(where);
        return query.fetch();
    }

    @Override
    public Page<NoticeRecord> search(final Pageable pageable, final Searchable searchable) {
        final QNoticeRecord qNotice = QNoticeRecord.noticeRecord;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<NoticeRecord> query = this.query().selectFrom(qNotice);
        query.where(where);
        return super.search(query, pageable);
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QNoticeRecord qNotice = QNoticeRecord.noticeRecord;
        where.and(
                super.equalsEnum(qNotice.mail.status, searchable, "mailStatus",
                        value -> SendStatus.valueOf(value)));
        where.and(
                super.equalsEnum(qNotice.system.status, searchable, "systemStatus",
                        value -> SendStatus.valueOf(value)));
        where.and(super.containsStr(qNotice.appCode, searchable, "appCode"));

        return where;
    }

    @Override
    protected Class<?> getModelClass() {
        return NoticeRecord.class;
    }

}
